package com.inossem.warehousestorage_inossem.activity.refund_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.refund_storage.extra.RefundStorageExtra;
import com.inossem.warehousestorage_inossem.bean.refundStorage.BatchSpecListBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageNewBatchBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageSaleBatchListBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageSaleOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.refundStorage.RefundStorageSaleNewBatch;
import com.inossem.warehousestorage_inossem.request.refundStorage.RefundStorageSaleSelectBatchRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.RefundStorageUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.ArrayList;
import java.util.List;

//销售退库批次详情
public class RefundStorageSaleMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_SERIAL = "serial";

    private static final String TYPE_INDEX = "index";

    private TextView title, serialNumber, materielCode, materielDescription, factory, inventoryAddress, orderNumber, hadRefundStorageNumber, batchNumber, pageInfo, showAndHide;

    private EditText refundStorageNumber;

    private Button previous, next;

    private String serialNumberStr, realSerialNumberStr, unit, mMaterielCode, mFactoraCode, mSaleNumber, mRetainDecimal;

    private int index;

    private RefundStorageSaleOverviewBean.SaleBodyBean.ItemListBean materielItem;

    private PercentLinearLayout batchLayout;

    private List<BatchSpecListBean> batchBeanList;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_refund_storage_sale_materiel_detail);
        initView(RefundStorageSaleMaterielDetailActivity.this);
        initData(RefundStorageSaleMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);

        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        factory = (TextView) activity.findViewById(R.id.factory);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        orderNumber = (TextView) activity.findViewById(R.id.orderNumber);
        hadRefundStorageNumber = (TextView) activity.findViewById(R.id.hadRefundStorageNumber);
        batchNumber = (TextView) activity.findViewById(R.id.batchNumber);
        pageInfo = (TextView) activity.findViewById(R.id.pageInfo);
        showAndHide = (TextView) activity.findViewById(R.id.showAndHide);
        refundStorageNumber = (EditText) activity.findViewById(R.id.refundStorageNumber);
        previous = (Button) activity.findViewById(R.id.previous);
        next = (Button) activity.findViewById(R.id.next);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_in_storage_allocating_add_operator_overview), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate(activity);
            }
        });
        refundStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                refundStorageNumber.setText("");
            }
        });
        previous.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index > 0) {
                    index--;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index < (RefundStorageUtils.getSaleMaterielListSize(activity) - 1)) {
                    index++;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        showAndHide.setOnClickListener((View v) -> {
            if (batchLayout.getVisibility() == View.GONE) {
                batchLayout.setVisibility(View.VISIBLE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_hide_information));
            } else if (batchLayout.getVisibility() == View.VISIBLE) {
                batchLayout.setVisibility(View.GONE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_show_information));
            }
        });
        getExtra(activity);
        getIndexBySerial(activity, realSerialNumberStr);
        getData(activity, TYPE_SERIAL);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            int indexTemp = RefundStorageUtils.getSaleIndexByMaterielCode(activity, mMaterielCode);
            if (indexTemp != -1) {
                if (indexTemp != index) {
                    index = indexTemp;
                    changeAndUpdate(activity);
                }
            } else {
                Utils.middleToast(activity, getResources().getString(R.string.activity_in_storage_receive_materiel_detail_not_find) + mMaterielCode + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_materiel));
            }
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        serialNumberStr = activity.getIntent().getStringExtra(RefundStorageExtra.SERIAL);
        realSerialNumberStr = activity.getIntent().getStringExtra(RefundStorageExtra.REAL_SERIAL);
        mSaleNumber = activity.getIntent().getStringExtra(RefundStorageExtra.SALE_NUMBER);
        LogUtils.i("mSaleNumber ====== " + mSaleNumber);
    }

    private void getIndexBySerial(Context context, String serialNumber) {
        index = RefundStorageUtils.getSaleIndexBySerial(context, serialNumber);
    }

    private void getData(BaseActivity context, String getMaterielInformationFromType) {
        switch (getMaterielInformationFromType) {
            case TYPE_SERIAL:
                materielItem = RefundStorageUtils.getSaleMaterielInformationBySerial(context, realSerialNumberStr);
                break;
            case TYPE_INDEX:
                materielItem = RefundStorageUtils.getSaleMaterielInformationByIndex(context, index);
                break;
        }
        mFactoraCode = materielItem.getFty_code();
        unit = materielItem.getUnit_name();
        serialNumber.setText(serialNumberStr);
        materielCode.setText(materielItem.getMat_code());
        mMaterielCode = materielItem.getMat_code();
        materielDescription.setText(materielItem.getMat_name());
        mRetainDecimal = materielItem.getDecimal_place();
        factory.setText(materielItem.getFty_code() + " - " + materielItem.getFty_name());
        inventoryAddress.setText(materielItem.getLocation_code() + " - " + materielItem.getLocation_name());
        orderNumber.setText(materielItem.getOrder_qty() + unit);
        hadRefundStorageNumber.setText(materielItem.getHave_return_qty() + unit);
        refundStorageNumber.setText(TextUtils.isEmpty(materielItem.getRefundNumber()) ? "" : (materielItem.getRefundNumber() + unit));
        batchNumber.setText(TextUtils.isEmpty(materielItem.getBatch()) ? context.getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number) : materielItem.getBatch());
        batchLayout.removeAllViews();
        if (!TextUtils.isEmpty(materielItem.getBatch())) {
            if (materielItem.getBatch().equals(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch))) {
                initNewBatchInfo(context, materielItem.getBatchList());
            } else {
                initBatchInfo(context, materielItem.getBatchInfoList());
            }

        }
        batchNumber.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                RefundStorageSaleSelectBatchRequest.request(context, materielItem.getMat_code(), materielItem.getFty_code(), new GsonBeanListener<RefundStorageSaleBatchListBean>() {
                    @Override
                    public void onSuccess(RefundStorageSaleBatchListBean bean) {
                        List<RefundStorageSaleBatchListBean.SaleBatchBodyBean> batchList = bean.getBody();
                        if (batchList == null || batchList.isEmpty()) {
                            Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_receive_list_no_message));
                            batchList = new ArrayList<>();
                        }
//                        else {
                        DialogUtils.getRefundStorageSaleBatchDialog(context, batchList, new DialogUtils.RefundStorageSaleBatchNumberListener() {
                            @Override
                            public void onSelect(Dialog dialog, String batchNumberStr, List<RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean> batchInfoList) {
                                batchNumber.setText(batchNumberStr);
                                List<BatchSpecListBean.InfoBean> list = new ArrayList<>();
                                for (RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean b : batchInfoList) {
                                    BatchSpecListBean.InfoBean infoBean = new BatchSpecListBean.InfoBean();
                                    infoBean.setText(b.getBatch_spec_name());
                                    infoBean.setValue(b.getBatch_spec_value());
                                    list.add(infoBean);
                                }
                                initBatchInfo(context, list);
                            }

                            @Override
                            public void onNewBatch() {
//                                    RefundStorageSaleNewBatch.request(context, mFactoraCode , mMaterielCode , mSaleNumber, new GsonBeanListener<RefundStorageNewBatchBean>() {
//                                        @Override
//                                        public void onSuccess(RefundStorageNewBatchBean bean) {
//                                            DialogUtils.getNewBatchDialog(context , bean , realSerialNumberStr , new DialogUtils.RefundStorageSaleNewBatchNumberListener() {
//                                                @Override
//                                                public void onNewBatch(List<RefundStorageNewBatchBean.DataBean.BatchBean> list) {
//                                                    batchNumber.setText(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch));
//                                                    batchBeanList = list;
//                                                    initNewBatchInfo(context, list);
//                                                }
//                                            }).show();
//                                        }
//                                    });

                                List<BatchSpecListBean> list = new ArrayList<>();
                                list.addAll(materielItem.getBatch_material_spec_list());
                                list.addAll(materielItem.getBatch_spec_list());
                                DialogUtils.getNewBatchDialog(context, list, realSerialNumberStr, new DialogUtils.RefundStorageSaleNewBatchNumberListener() {
                                    @Override
                                    public void onNewBatch(List<BatchSpecListBean> list) {
                                        batchNumber.setText(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch));
                                        batchBeanList = list;
                                        initNewBatchInfo(context, list);
                                    }
                                }).show();
                            }
                        }).show();
//                        }
                    }
                });
            }
        });

        pageInfo.setText(RefundStorageUtils.getSaleMaterielListSize(context) + " | " + (index + 1));
        if (index <= 0) {
            previous.setText(getResources().getString(R.string.activity_receive_result_back));
        } else {
            previous.setText(getResources().getString(R.string.activity_inventory_item_previous_page));
        }
        if (index >= (RefundStorageUtils.getSaleMaterielListSize(context) - 1)) {
            next.setText(getResources().getString(R.string.activity_receive_result_back));
        } else {
            next.setText(getResources().getString(R.string.activity_inventory_item_next_page));
        }
    }

    //选择的批次信息
    private void initBatchInfo(Context context, List<BatchSpecListBean.InfoBean> batchInfoList) {
        if (batchInfoList != null && !batchInfoList.isEmpty()) {
            batchLayout.removeAllViews();
            for (int i = 0; i < batchInfoList.size(); i++) {
                BatchSpecListBean.InfoBean batchInfo = batchInfoList.get(i);
                RefundStorageUtils.createTextView(context, batchLayout, batchInfo.getText(), batchInfo.getValue());
            }
        }
    }

    //新建批次信息
    private void initNewBatchInfo(Context context, List<BatchSpecListBean> batchInfoList) {
        if (batchInfoList != null && !batchInfoList.isEmpty()) {
            batchLayout.removeAllViews();
            for (int i = 0; i < batchInfoList.size(); i++) {
                BatchSpecListBean batchInfo = batchInfoList.get(i);
                RefundStorageUtils.createTextView(context, batchLayout, batchInfo.getBatch_spec_name(), batchInfo.getText());
            }
        }
    }

    private void updateInfo(Context context) {
        materielItem.setRefundNumber(refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim());
        materielItem.setBatch(batchNumber.getText().toString());
        int batchCount = batchLayout.getChildCount();
        if (!batchNumber.getText().toString().equals(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch))) {
            List<BatchSpecListBean.InfoBean> batchInfoList = new ArrayList<>();
            for (int i = 0; i < batchCount; i++) {
                View view = batchLayout.getChildAt(i);
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String value = ((TextView) view.findViewById(R.id.text)).getText().toString();
                BatchSpecListBean.InfoBean batchInfo = new BatchSpecListBean.InfoBean();
                batchInfo.setText(name);
                batchInfo.setValue(value);
                batchInfoList.add(batchInfo);
            }
            materielItem.setBatchInfoList(batchInfoList);
            materielItem.setBatchList(new ArrayList<>());
        } else {
            if (batchBeanList != null) {
                materielItem.setBatchList(batchBeanList);
                materielItem.setBatchInfoList(new ArrayList<>());
            }

        }
        RefundStorageUtils.updateSaleRefundStorageItem(context, materielItem);
        LogUtils.i("afterSP ============= " + SPUtils.getSaleRefundStorageInformation(context));
    }

    private String check(Context context) {
        String refundStorageNumberStr = refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim();
//        if (TextUtils.isEmpty(refundStorageNumberStr)) {
//            return "退库数量不可以为空";
//        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && !RegexUtils.checkDecimal(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_is_illegal);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && RegexUtils.checkZero(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_must_be_greater_than_zero);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && !Utils.checkRetainDecimal(refundStorageNumberStr, mRetainDecimal)) {
//            Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + serialNumber + );
            return String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
        }
        if (!TextUtils.isEmpty(refundStorageNumberStr)) {
            float maxNumber = Float.parseFloat(materielItem.getOrder_qty()) - Float.parseFloat(materielItem.getHave_return_qty());
            float refundStoragetNumberFloat = Float.parseFloat(refundStorageNumberStr);
            if (refundStoragetNumberFloat > maxNumber) {
                return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_can_not_be_greater_than_the_number_of_outgoing_libraries_minus_the_number_of_restores);
            }
        }

        String batchNumberStr = batchNumber.getText().toString();
        if (context.getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number).equals(batchNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number);
        }

        return null;
    }

    private void backAndUpdate(Context context) {
        String checkResult = check(context);
        if (checkResult == null) {
            updateInfo(context);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + getResources().getString(R.string.activity_change_storage_materiel_detail_whether_to_force_out), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    RefundStorageSaleMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void changeAndUpdate(BaseActivity activity) {
        String checkResult = check(activity);
        if (checkResult == null) {
            updateInfo(activity);
            getData(activity, TYPE_INDEX);
        } else {
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    getData(activity, TYPE_INDEX);
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate(RefundStorageSaleMaterielDetailActivity.this);
    }
}
